package com.liukang.item.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liukang.common.dto.PageDTO;
import com.liukang.item.constatnts.MqConstants;
import com.liukang.item.pojo.Item;
import com.liukang.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/list")
    public PageDTO itemList(@RequestParam Integer page, @RequestParam Integer size) {
        IPage<Item> iPage = new Page<>(page, size);
        itemService.page(iPage, null);
        PageDTO pageDTO = new PageDTO();
        pageDTO.setList(iPage.getRecords());
        pageDTO.setTotal(iPage.getTotal());
        return pageDTO;
    }

    @GetMapping("/{id}")
    public Item itemById(@PathVariable("id") Long id) {
        return itemService.getById(id);
    }

    @PostMapping
    public Boolean itemInsert(@RequestBody Item item) {
//        System.out.println(item);
        return itemService.save(item);
    }

    @PutMapping("/status/{id}/{status}")
    public void itemUpdateByIdStatus(@PathVariable Long id,@PathVariable Integer status){
        Item item = new Item();
        item.setId(id);
        item.setStatus(status);
        itemService.updateById(item);
        if (item.getStatus() == 1){
            rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE,MqConstants.ITEM_INSERT_KEY,id);
        }else if (item.getStatus() == 2){
            rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE,MqConstants.ITEM_DELETE_KEY,id);
        }
    }

    @PutMapping
    public Boolean itemUpdate(@RequestBody Item item){
        return itemService.updateById(item);
    }

    @DeleteMapping("{id}")
    public Boolean itemDeleteById(@PathVariable Long id){
        return itemService.removeById(id);
    }
}
